use actix_web::{http::StatusCode, HttpResponse, ResponseError};
use derive_more::{Display, From};
use std::num::TryFromIntError;
use std::time::SystemTimeError;

#[derive(Display, From, Debug)]
pub enum MyError {
    NotAuthed,
    NotFound,
    Msg(String),
    SystemTimeError(SystemTimeError),
    TryFromIntError(TryFromIntError),
    ConfigError(config::ConfigError),
    RedisError(redis::RedisError),
    ReqwestError(reqwest::Error),
    ReqwestToStrError(reqwest::header::ToStrError),
}

impl From<MyError> for std::io::Error {
    fn from(err: MyError) -> Self {
        std::io::Error::new(std::io::ErrorKind::Other, format!("{}", err))
    }
}
impl ResponseError for MyError {
    fn error_response(&self) -> HttpResponse {
        match *self {
            MyError::Msg(ref err) => HttpResponse::InternalServerError().body(err.to_string()),
            MyError::NotAuthed => HttpResponse::Unauthorized().finish(),
            //MyError::RedisError=>HttpResponse::InternalServerError().body(format!(
            MyError::NotFound => HttpResponse::NotFound().finish(),
            _ => HttpResponse::InternalServerError().body(format!("{:?}", self)),
        }
    }
}
